function varargout = common (varargin)

   ## usage:  [I1 I2 ...] = common (id1, id2, ...)
   ## define common period

   varargout = cell(1,nargin) ;

   if (nargin > 2)
      [varargout{1:nargin-1}] = common(varargin{1:nargin-1}) ;
      varargout{nargin} = all(isfinite(varargin{nargin}), 2) ;
      for i=1:nargin-1
   	 [I1 I2] = common(varargin{i}, varargin{nargin}) ;
	 varargout{i} = varargout{i} & I1 ;
	 varargout{nargin} = varargout{nargin} & I2 ;
      endfor 
      return ;
   elseif nargin < 2
      varargout{1} = true(rows(varargin{1}),1) ;
      return ;
   endif 

   id1 = varargin{1} ; id2 = varargin{2} ;

   if columns(id1) < 2
      id1 = [id1 ones(rows(id1), 2)] ;
   endif
   if columns(id1) < 3
      id1 = [id1 ones(rows(id1), 1)] ;
   endif
   if columns(id2) < 2
      id2 = [id2 ones(rows(id2), 2)] ;
   endif
   if columns(id2) < 3
      id2 = [id2 ones(rows(id2), 1)] ;
   endif
   if L1 = (datenum(id1(1,:)) > datenum(id1(end,:)))
      id1 = flipud(id1) ;
   endif
   if L2 = (datenum(id2(1,:)) > datenum(id2(end,:)))
      id2 = flipud(id2) ;
   endif

   if lex_cmp(id1(1,:), id2(1,:)) == 1
      l = id1(1,:) ;
   else
      l = id2(1,:) ;
   endif
   if lex_cmp(id1(end,:), id2(end,:)) == 1
      u = id2(end,:) ;
   else
      u = id1(end,:) ;
   endif

   nc = min(columns(id1), columns(id2)) ;
   l = l(:,1:nc) ;
   u = u(:,1:nc) ;
   id1 = id1(:,1:nc) ;
   id2 = id2(:,1:nc) ;

   I1 = date_cmp(repmat(l,rows(id1),1), id1) & date_cmp(id1, repmat(u,rows(id1),1)) ;
   I2 = date_cmp(repmat(l,rows(id2),1), id2) & date_cmp(id2, repmat(u,rows(id2),1)) ;
   if L1
      I1 = flipud(I1) ;
   endif
   if L2
      I2 = flipud(I2) ;
   endif

   varargout{1} = I1 ;
   varargout{2} = I2 ;

endfunction


function c = lex_cmp (a, b)

##       c = lex_cmp (a, b)
##         =  1 if  a  is greater than  b  for lexicographic order
##         = -1 if  b  is greater than  a  for lexicographic order
##         =  0 if  a  and  b  are equal
## 

## Author:        Etienne Grossmann  <etienne@isr.ist.utl.pt>
## Last modified: April 2001

c = 0 ;

na = prod (size (a)) ;
nb = prod (size (b)) ;
m = min (na, nb) ;
m = find (a(1:m) - b(1:m));

if isempty (m),
  if      na < nb, c = -1 ;
  elseif  na > nb, c =  1 ;
  end
else
  if      a(m(1)) < b(m(1)), c = -1 ;
  elseif  a(m(1)) > b(m(1)), c =  1 ;
  end
end

endfunction
